package org.middleware.service.system;

import org.middleware.entity.system.SysUsers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@Service
public class AvatarService {

    @Value("${file.upload.path}")
    private String uploadPath;

    @Value("${file.upload.allowed-types}")
    private String allowedTypes;

    @Value("${file.upload.access-url}")
    private String accessUrl;

    @Value("${spring.servlet.multipart.max-file-size}")
    private String maxSize;

    @Value("${api.base.url}")
    private String apiBaseUrl;

    private List<String> allowedTypeList;
    private long maxSizeBytes;

    @Autowired
    private SysUsersService usersService;

    @PostConstruct
    public void init() {
        // 初始化允许的文件类型列表
        allowedTypeList = Arrays.asList(allowedTypes.split(","));

        // 转换最大文件大小
        maxSizeBytes = parseSize(maxSize);
    }

    /**
     * 保存用户头像
     */
    public String saveAvatar(int userId, MultipartFile file) throws IOException {
        // 验证文件
        validateFile(file);

        // 获取用户信息
        SysUsers user = usersService.getUserById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 删除旧头像
        deleteOldAvatar(user.getAvatar());

        // 生成新文件名
        String newFilename = generateFilename(userId, file.getOriginalFilename());
        String avatarUrl = getAvatarFile(newFilename);

        // 保存文件
        Path filePath = Paths.get(uploadPath, newFilename);
        Files.createDirectories(filePath.getParent());
        file.transferTo(filePath.toFile());

        // 保存文件名到数据库
        user.setAvatar(newFilename);
        usersService.updateUserInfo(user);

        return avatarUrl;
    }

    /**
     * 验证文件
     */
    private void validateFile(MultipartFile file) {
        if (file.isEmpty()) {
            throw new RuntimeException("文件不能为空");
        }

        // 验证文件类型
        String contentType = file.getContentType();
        if (contentType == null || !allowedTypeList.contains(contentType)) {
            throw new RuntimeException("不支持的文件类型，仅支持: " + allowedTypes);
        }

        // 验证文件大小
        if (file.getSize() > maxSizeBytes) {
            throw new RuntimeException("文件大小不能超过 " + maxSize);
        }
    }

    /**
     * 生成文件名
     */
    private String generateFilename(int userId, String originalFilename) {
        String extension = getFileExtension(originalFilename);
        String uuid = UUID.randomUUID().toString().replace("-", "");
        return "avatar_" + userId + "_" + uuid + extension;
    }

    /**
     * 获取文件扩展名
     */
    private String getFileExtension(String filename) {
        int dotIndex = filename.lastIndexOf(".");
        if (dotIndex > 0) {
            return filename.substring(dotIndex);
        }
        return ".jpg"; // 默认扩展名
    }

    /**
     * 删除旧头像
     */
    public void deleteOldAvatar(String oldAvatarPath) {
        if (oldAvatarPath != null && !oldAvatarPath.isEmpty()) {
            File oldFile = new File(uploadPath, oldAvatarPath);
            if (oldFile.exists()) {
                boolean deleted = oldFile.delete();
                if (!deleted) {
                    System.err.println("删除旧头像失败: " + oldFile.getAbsolutePath());
                }
            }
        }
    }

    /**
     * 解析文件大小字符串
     */
    private long parseSize(String size) {
        size = size.toUpperCase();
        if (size.endsWith("MB")) {
            return Long.parseLong(size.replace("MB", "").trim()) * 1024 * 1024;
        } else if (size.endsWith("KB")) {
            return Long.parseLong(size.replace("KB", "").trim()) * 1024;
        } else {
            return Long.parseLong(size.trim());
        }
    }

    /**
     * 获取头像文件
     */
    public String getAvatarFile(String filename) {
        return apiBaseUrl + accessUrl + filename;
    }
}
